//
//  HLVideoPostMediaView.m
//  YueYue
//
//  Created by hulu001 on 2024/3/8.
//

#import "HLVideoPostMediaView.h"
#import "HLImageStatusView.h"
#import "HLPickerManager.h"
#import "HLVideoOptionRequest.h"
#import "HLVideoPostViewController.h"

@interface HLVideoPostMediaView ()
@property (nonatomic, strong) HLVideoPostModel *squarePost;

@property (nonatomic, strong) QMUIButton *uploadVideoButton;
@property (nonatomic, strong) QMUIButton *uploadLinkButton;

@property (nonatomic, strong) HLPickerManager *pickerVideoManager;
@property (nonatomic, strong) NSMutableArray<HXPhotoModel *> *photos;

@end

@implementation HLVideoPostMediaView

- (instancetype)initWithPost:(HLVideoPostModel *)post
{
    self = [super initWithFrame:CGRectZero];
    if (self) {
        self.squarePost = post;
        
        self.pickerVideoManager = [[HLPickerManager alloc] initWithType:HXPhotoManagerSelectedTypeVideo avatar:NO];
        [_pickerVideoManager updateMaxNum:1 photos:nil];
        [self setupView];
    }
    return self;
}

- (void)setupView
{
    
    
    self.uploadVideoButton = [[QMUIButton alloc] init];
    [_uploadVideoButton setTitle:@"上传视频" forState:UIControlStateNormal];
    [_uploadVideoButton setImage:UIImageMake(@"square_post_video") forState:UIControlStateNormal];
    [_uploadVideoButton setTitleColor:HLTextColor3 forState:UIControlStateNormal];
    [_uploadVideoButton.titleLabel setFont:UIFontMediumMake(11)];
    _uploadVideoButton.imagePosition = QMUIButtonImagePositionTop;
    _uploadVideoButton.spacingBetweenImageAndTitle = 4;
    _uploadVideoButton.cornerRadius = 8;
    [_uploadVideoButton setBackgroundColor:HLBackgroundColor];
    [_uploadVideoButton addTarget:self action:@selector(uploadVideoAction) forControlEvents:UIControlEventTouchUpInside];
    
    self.uploadLinkButton = [[QMUIButton alloc] init];
    [_uploadLinkButton setTitle:@"链接视频" forState:UIControlStateNormal];
    [_uploadLinkButton setImage:UIImageMake(@"square_post_link") forState:UIControlStateNormal];
    [_uploadLinkButton setTitleColor:HLTextColor3 forState:UIControlStateNormal];
    [_uploadLinkButton.titleLabel setFont:UIFontMediumMake(11)];
    _uploadLinkButton.imagePosition = QMUIButtonImagePositionTop;
    _uploadLinkButton.spacingBetweenImageAndTitle = 4;
    _uploadLinkButton.cornerRadius = 8;
    [_uploadLinkButton setBackgroundColor:HLBackgroundColor];
    [_uploadLinkButton addTarget:self action:@selector(uploadLinkAction) forControlEvents:UIControlEventTouchUpInside];
    
    
}


#pragma mark - link option
- (void)uploadLinkAction
{
    NSString *videoLink = [[UIPasteboard generalPasteboard] string];
    if (videoLink.length == 0){
        [QMUITips showWithText:@"还没有视频链接，可以粘贴"];
        return;
    }
    
    [QMUITips showLoading:@"视频链接转换中..." inView:self];
    HLVideoOptionRequest *videoOptionRequest = [[HLVideoOptionRequest alloc] initWithType:HLVideoOptionTypeVideoAnalysis params:@{@"videoUrl":videoLink}];
    [videoOptionRequest startWithCompletionBlockWithSuccess:^(__kindof HLVideoOptionRequest * _Nonnull request) {
        [QMUITips hideAllTips];
        if (request.isSuccess) {
            NSDictionary *data = request.result[@"data"];
            NSString *videoUrls = data[@"videoUrls"];
            NSString *coverUrls = data[@"coverUrls"];
            NSString *content = data[@"title"];
            self.squarePost.videoLink = videoUrls;
            self.squarePost.videoCoverUrl = coverUrls;
            HLVideoPostViewController *postVC = (HLVideoPostViewController *)self.qmui_viewController;
            [postVC updateWithVideoLinkContent:content];
            HLImageStatusView *videoView = [[HLImageStatusView alloc] init];
            [videoView.imageView sd_setImageWithURL:[NSURL URLWithString:coverUrls]];
            videoView.layer.cornerRadius = 8;
            videoView.playVideoView.hidden = NO;
            [videoView.closeButton setBackgroundColor:[UIColorBlack colorWithAlphaComponent:0.4]];
            [videoView.closeButton addTarget:self action:@selector(deleteLink) forControlEvents:UIControlEventTouchUpInside];
            [videoView.previewButton addTarget:self action:@selector(previewLink:) forControlEvents:UIControlEventTouchUpInside];
            [self.uploadLinkButton addSubview:videoView];
            [videoView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.mas_equalTo(0);
            }];
        } else {
            [QMUITips showWithText:@"你粘贴的，不是一个视频链接"];
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [QMUITips hideAllTips];
    }];
    
    
}

- (void)deleteLink
{
    for (UIView *subView in self.uploadVideoButton.subviews) {
        if ([subView isKindOfClass:[HLImageStatusView class]]){
            [subView removeFromSuperview];
        }
    }
    _squarePost.videoLink = @"";
}

- (void)previewLink:(QMUIButton *)btn
{
    HXPhotoManager *photoManager = [HXPhotoManager managerWithType:HXPhotoManagerSelectedTypePhotoAndVideo];

    HXCustomAssetModel *model = [HXCustomAssetModel assetWithLocalVideoURL:[NSURL URLWithString:_squarePost.videoLink] selected:YES];
    
    [photoManager addCustomAssetModel:@[model]];
    [HLPickerManager previewWithManager:photoManager index:0 controller:self.qmui_viewController];
}

#pragma mark - video option
- (void)uploadVideoAction
{
    MJWeakSelf;
    [self.pickerVideoManager showWithController:self.qmui_viewController block:^(NSArray<HXPhotoModel *> *photos) {
        for (HXPhotoModel *photo in photos) {
  
            [photo getVideoURLWithSuccess:^(NSURL * _Nullable URL, HXPhotoModelMediaSubType mediaType, BOOL isNetwork, HXPhotoModel * _Nullable model) {
                weakSelf.squarePost.videoFileUrl = [HLHelper changeVideoPhasset:model.asset];
                if (weakSelf.squarePost.videoCover){
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf updateVideo];
                    });
                }
            } failed:nil];
            [photo getImageWithSuccess:^(UIImage * _Nullable image, HXPhotoModel * _Nullable model, NSDictionary * _Nullable info) {
                weakSelf.squarePost.videoCover = image;
                if (weakSelf.squarePost.videoFileUrl.length > 0){
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf updateVideo];
                    });
                }
            } failed:nil];
        }
    }];
}

- (void)updateVideo
{
    HLImageStatusView *videoView = [[HLImageStatusView alloc] init];
    videoView.imageView.image = _squarePost.videoCover;
    videoView.layer.cornerRadius = 8;
    videoView.playVideoView.hidden = NO;
    [videoView.closeButton setBackgroundColor:[UIColorBlack colorWithAlphaComponent:0.4]];
    [videoView.closeButton addTarget:self action:@selector(deleteVideo) forControlEvents:UIControlEventTouchUpInside];
    [videoView.previewButton addTarget:self action:@selector(previewVideo:) forControlEvents:UIControlEventTouchUpInside];
    [self.uploadVideoButton addSubview:videoView];
    [videoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
}

- (void)deleteVideo
{
    for (UIView *subView in self.uploadVideoButton.subviews) {
        if ([subView isKindOfClass:[HLImageStatusView class]]){
            [subView removeFromSuperview];
        }
    }
    _squarePost.videoCover = nil;
    _squarePost.videoFileUrl = @"";
}

- (void)previewVideo:(QMUIButton *)btn
{
    HXPhotoManager *photoManager = [HXPhotoManager managerWithType:HXPhotoManagerSelectedTypePhotoAndVideo];

    HXCustomAssetModel *model = [HXCustomAssetModel assetWithLocalVideoURL:[NSURL fileURLWithPath:_squarePost.videoFileUrl] selected:YES];
    [photoManager addCustomAssetModel:@[model]];
    [HLPickerManager previewWithManager:photoManager index:0 controller:self.qmui_viewController];
}


- (void)updateMediaTypeWithPostType:(NSInteger)type
{
   CGFloat width = (SCREEN_WIDTH - 72)/3;
   _squarePost.opus = [NSArray array];
   [self qmui_removeAllSubviews];
   [self deleteVideo];
   [self deleteLink];
   switch (type) {
       case 2:
           _squarePost.dynamicType = @"3";
           [self addSubview:_uploadVideoButton];
           [_uploadVideoButton mas_remakeConstraints:^(MASConstraintMaker *make) {
               make.size.mas_equalTo(CGSizeMake(120, 160));
               make.left.top.bottom.mas_equalTo(0);
           }];
           break;
       case 1:
           _squarePost.dynamicType = @"3";
           [self addSubview:_uploadLinkButton];
           [_uploadLinkButton mas_remakeConstraints:^(MASConstraintMaker *make) {
               make.size.mas_equalTo(CGSizeMake(120, 160));
               make.left.top.bottom.mas_equalTo(0);
           }];
           break;
   }
}

@end
